package com.hyj.jpdy.grap.rss;

import java.util.LinkedList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.hyj.jpdy.grap.rss.bean.Item;
import com.hyj.jpdy.grap.rss.bean.RssChannel;
import com.hyj.util.HttpUtil;


public class RssUtil {
	
	@SuppressWarnings("unchecked")
	public static RssChannel parserRss(String xml){
		RssChannel rss  = new RssChannel();
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(xml);
		
		Element root = doc.getRootElement();
		Element channel = root.element("channel");
		String title = channel.element("title").getTextTrim();
		rss.setTitle(title);
		
		String description = channel.elementText("description");
		rss.setDescription(description);
		
		String link = channel.elementTextTrim("link");
		rss.setLink(link);
		
		String lastBuildDate = channel.elementTextTrim("lastBuildDate");
		rss.setLastBuildDate(lastBuildDate);
		
		String generator = channel.elementText("generator");
		rss.setGenerator(generator);
		
		String language = channel.elementText("language");
		rss.setLanguage(language);
		
		String copyright = channel.elementText("copyright");
		rss.setCopyright(copyright);
		
		String pubDate = channel.elementText("pubDate");
		rss.setPubDate(pubDate);
		
		
		List<Item> list = new LinkedList<Item>();
		List<Element> eles = doc.selectNodes("//item");
		for(Element e :eles){
			Item item = new Item();
			
			String ititle = e.elementText("title");
			item.setTitle(ititle);
			
			String ilink = e.elementText("link");
			item.setLink(ilink);
			
			String idescription = e.elementText("description");
			item.setDescription(idescription);
			
			String iauthor = e.elementText("author");
			item.setAuthor(iauthor);
			
			String ipubDate = e.elementText("pubDate");
			item.setPubDate(ipubDate);
			
			String iguid = e.elementText("guid");
			item.setGuid(iguid); 
			
			list.add(item); 
		}
		    rss.setItems(list);
		} catch (Exception e1) {
			e1.printStackTrace();
			return null;
		}
		return  rss;
	}
	
	
    public static void main(String[] args) throws Exception{
    	String url = "http://www.qiushibaike.com/hot/rss";
		String  content = HttpUtil.getRemoteResp(url,"UTF-8");
		System.out.println(content);
		RssChannel rss = parserRss(content);
		String title = rss.getTitle();
		System.out.println("栏目名称："+title);
		List<Item> list = rss.getItems();
		
		for(Item i:list){
			System.out.println("===============================================");
			System.out.println(i.getTitle());
			System.out.println("内容：---");
			System.out.println(i.getDescription());
		}
		
		
    }
}
